package com.example.walletmodule.service.impl;

import com.example.walletmodule.mappers.WalletDetailsDao;
import com.example.walletmodule.entity.ConsumptionDTO;
import com.example.walletmodule.entity.WalletDetailsEntity;
import com.example.walletmodule.entity.WalletEntity;
import com.example.walletmodule.service.WalletDetailsService;
import com.example.walletmodule.service.WalletService;
import com.example.walletmodule.util.CommonResult;
import com.example.walletmodule.util.Constants;
import com.example.walletmodule.util.RedisUtil;
import com.example.walletmodule.util.SnowflakeUtils;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.List;


@Service("walletDetailsService")
public class WalletDetailsServiceImpl extends ServiceImpl<WalletDetailsDao, WalletDetailsEntity> implements WalletDetailsService {

	@Resource
	private WalletDetailsDao walletDetailsDao;
	@Resource
	private WalletService walletService;
	@Resource
	private RedisUtil redisUtil;

	public CommonResult<Boolean> comsuption(ConsumptionDTO consumptionDTO) {

		// 余额消费   用用户id查询账户余额 和版本号 用于乐观锁 防止其他的设备同时修改金导致脏数据
		WalletEntity wallet = walletService.getByUserId(consumptionDTO.getUserId());
		// 乐观锁
		Integer version = wallet.getWalletVersion();
		// 余额
		BigDecimal balance = wallet.getWalletBalance();
		//开始结算  获取rediskey 如果是空的就 设置一个新的redis key 并且开始业务 用来防止多个请求同时结算 或者退款  如果存在该键值对 则说明有人正在结算
		if(ObjectUtils.isEmpty(redisUtil.get("IS_SETTLEING"))){
			redisUtil.set("IS_SETTLEING", "1");
			// 判断消费类型（用余额消费还是用直接用银行卡消费）
			if (Constants.PAY_WAY.PAY_FOR_BALANCE.equals(consumptionDTO.getPayWay())) {
				// 消费金额
				BigDecimal payMoney = consumptionDTO.getMoney();
				// 消费金额大于余额 提示不能消费
				if (payMoney.compareTo(balance) == 1) {
					// 结算完成 redis删除该键值对
					redisUtil.del("IS_SETTLEING");
					return CommonResult.fail(false, "消费金额大于余额，扣款失败");
				} else {
					wallet.setSurplus(payMoney.subtract(balance));
					version++;
					wallet.setNewVersion(version);
					// 根据版本号修改 余额(乐观锁)
					int update = walletService.updateWallet(wallet);
					if (update <= 0) {
						return CommonResult.fail(false, "消费失败，当前用户正在消费");
					}
					// 增加商品交易订单
					/*addGoodsOrder()*/
					// 消费成功就往明细表中插入数据
					WalletDetailsEntity walletDetailsEntity = new WalletDetailsEntity();
					walletDetailsEntity.setDetailsId(SnowflakeUtils.getId());
					walletDetailsEntity.setWalletId(wallet.getWalletId());
					walletDetailsEntity.setWalletMoney(wallet.getWalletBalance());
					walletDetailsEntity.setPayWay(consumptionDTO.getPayWay());
					walletDetailsEntity.setUserId(consumptionDTO.getUserId());
					walletDetailsEntity.setMoney(consumptionDTO.getMoney());
					walletDetailsDao.insert(walletDetailsEntity);
					// 结算完成 redis删除该键值对
					redisUtil.del("IS_SETTLEING");
					return CommonResult.success(true, "消费成功");
				}

			} else if (Constants.PAY_WAY.PAY_FOR_BANK.equals(consumptionDTO.getPayWay())) {
				//银行卡消费
				return null;
			}

		}else {
			return CommonResult.fail(false, "消费失败，当前用户正在消费");
		}

		return CommonResult.fail(false, "未知消费");
	}

	public CommonResult<List<WalletDetailsEntity>> queryWalletDetails(WalletDetailsEntity walletDetailsEntity) {
		return CommonResult.success(walletDetailsDao.queryWalletDetails(walletDetailsEntity), "查询成功");
	}

	public CommonResult<Boolean> refundMoney(ConsumptionDTO consumptionDTO) {

		// 余额消费   用用户id查询账户余额 和版本号 用于乐观锁 防止其他的设备同时修改金导致脏数据
		WalletEntity wallet = walletService.getByUserId(consumptionDTO.getUserId());
		// 乐观锁
		Integer version = wallet.getWalletVersion();
		// 余额
		BigDecimal balance = wallet.getWalletBalance();
		// 判断消费类型（时退款到银行卡还是退款到余额）
		if (Constants.PAY_WAY.REFUND_BALANCE.equals(consumptionDTO.getPayWay())) {
			// 退款金额
			BigDecimal payMoney = consumptionDTO.getRefundMoney();

			wallet.setSurplus(payMoney.add(balance));
			version++;
			wallet.setNewVersion(version);
			// 根据版本号修改 余额(乐观锁)
			int update = walletService.updateWallet(wallet);
			if (update <= 0) {
				return CommonResult.fail(false, "退款失败，当前状态正在消费或者退款中");
			}
			// 增加商品交易订单
			/*addGoodsOrder()*/
			// 消费成功就往明细表中插入数据
			WalletDetailsEntity walletDetailsEntity = new WalletDetailsEntity();
			walletDetailsEntity.setDetailsId(SnowflakeUtils.getId());
			walletDetailsEntity.setWalletId(wallet.getWalletId());
			walletDetailsEntity.setWalletMoney(wallet.getWalletBalance());
			walletDetailsEntity.setPayWay(consumptionDTO.getPayWay());
			walletDetailsEntity.setUserId(consumptionDTO.getUserId());
			walletDetailsEntity.setMoney(consumptionDTO.getRefundMoney());
			walletDetailsDao.insertRefund(walletDetailsEntity);
			return CommonResult.success(true, "退款至余额成功");


		} else if (Constants.PAY_WAY.PAY_FOR_BANK.equals(consumptionDTO.getPayWay())) {
			//退款到银行卡 ----------------
			return CommonResult.success(true, "退款至银行卡成功");
		}
		return CommonResult.fail(false, "未知消费");
	}
}